<?
##########################################################################
## BACKUP.PHP
##########################################################################

require("adm_header.php");
require("libs/zip.lib.php");
writeCommonAdminTable(LA_ADMIN_BACKUP_TITLE,1);
echo LA_ADMIN_BACKUP_DESCR;
?>
<br /><br />

<?
if ($set_demo)
{
	echo "<p><font color='red'>System in demo mode. No changes will be saved.</font></p>";
}

if ($set_backup)
{

if (!file_exists("config/backup/.htaccess") && !$set_demo)
{
	echo "<p><b><font color='red'>".LA_ADMIN_WARNING.":</font></b>".LA_ADMIN_BACKUP_WARNING."</p>";
}
	
	
$backup_dir="$set_path/admin/config/backup/";
$lReturnArray=checkWrite($backup_dir,$set_chmod,0);
if ($lReturnArray["writeable"]==false)
{
	print(" <b>Error</b><br />Backupdir is not set to chmod 777 (writeable) ");
}
else 
{
	print("Permissions are set correct: <a href='adm_backup.php?backup=1'><b><u>Start backup</u></b></a>");		
}
	

function mysqlbackup($host,$dbname, $uid, $pwd, $output, $structure_only)
{

	//this function creates a text file (or output to a HTTP connection), that when parsed through MYSQL's telnet client, will re-create the entire database

	//Parameters:
        //      $host: usually "localhost" but depends on where the MySQL database engine is mounted
	//	$dbname : The MySQL database name 
	//	$uid : the database's username (not your account's), leave blank if none is required
	//	$pwd : the database's password 
	//	$output : this is the complete filespec for the output text file, or if you want the result SQL to be sent back to the browser, leave blank.
	//	$structure_only : set this to true if you want just the schema of the database (not the actual data) to be output.

	// **************
	// IMPORTANT: If you use this function, for personal or commercial use, AND you feel an overwhelming sense of gratitude that someone actually took the time and wrote it,
	// immediately go to your paypal account and send me $10 with a small comment of how and how much it helped! Set the payment recipient to woodystanford@yahoo.com .
	// **************

	if (strval($output)!="") $fptr=fopen($output,"w"); else $fptr=false;

	//connect to MySQL database
	$con=mysql_connect($host,$uid, $pwd);
	$db=mysql_select_db($dbname,$con);

	//open back-up file ( or no file for browser output)

	//set up database
	out($fptr, "create database $dbname;\n\n");

	//enumerate tables
	$res=mysql_list_tables($dbname);
	$nt=mysql_num_rows($res);

	for ($a=0;$a<$nt;$a++)
	{
		$row=mysql_fetch_row($res);
		$tablename=$row[0];

		//start building the table creation query
		$sql="create table $tablename\n(\n";

		$res2=mysql_query("select * from $tablename",$con);
		$nf=mysql_num_fields($res2);
		$nr=mysql_num_rows($res2);

		$fl="";

		//parse the field info first
		for ($b=0;$b<$nf;$b++)
		{
			$fn=mysql_field_name($res2,$b);
			$ft=mysql_fieldtype($res2,$b);
			$fs=mysql_field_len($res2,$b);
			$ff=mysql_field_flags($res2,$b);

			$sql.="	$fn ";

			$is_numeric=false;
			switch(strtolower($ft))
			{
				case "int":
					$sql.="int";
					$is_numeric=true;
					break;

				case "blob":
					$sql.="text";
					$is_numeric=false;
					break;

				case "real":
					$sql.="real";
					$is_numeric=true;
					break;

				case "string":
					$sql.="varchar($fs)";
					$is_numeric=false;
					break;

				case "unknown":
					switch(intval($fs))
					{
						case 4:	//little weakness here...there is no way (thru the PHP/MySQL interface) to tell the difference between a tinyint and a year field type
							$sql.="tinyint";
							$is_numeric=true;
							break;

						default:	//we could get a little more optimzation here! (i.e. check for medium ints, etc.)
							$sql.="int";
							$is_numeric=true;
							break; 
					}
					break;

				case "timestamp":
					$sql.="timestamp"; 
					$is_numeric=true;
					break;

				case "date":
					$sql.="date"; 
					$is_numeric=false;
					break;

				case "datetime":
					$sql.="datetime"; 
					$is_numeric=false;
					break;

				case "time":
					$sql.="time"; 
					$is_numeric=false;
					break;

				default: //future support for field types that are not recognized (hopefully this will work without need for future modification)
					$sql.=$ft;
					$is_numeric=true; //I'm assuming new field types will follow SQL numeric syntax..this is where this support will breakdown 
					break;
			}

			//VERY, VERY IMPORTANT!!! Don't forget to append the flags onto the end of the field creator

			if (strpos($ff,"unsigned")!=false)
			{
				//timestamps are a little screwy so we test for them
				if ($ft!="timestamp") $sql.=" unsigned";
			}

			if (strpos($ff,"zerofill")!=false)
			{
				//timestamps are a little screwy so we test for them
				if ($ft!="timestamp") $sql.=" zerofill";
			}

			if (strpos($ff,"auto_increment")!=false) $sql.=" auto_increment";
			if (strpos($ff,"not_null")!=false) $sql.=" not null";
			if (strpos($ff,"primary_key")!=false) $sql.=" primary key";

			//End of field flags

			if ($b<$nf-1)
			{
				$sql.=",\n";
				$fl.=$fn.", ";
			}
			else
			{
				$sql.="\n);\n\n";
				$fl.=$fn;
			}

			//we need some of the info generated in this loop later in the algorythm...save what we need to arrays
			$fna[$b]=$fn;
			$ina[$b]=$is_numeric;
			
		}

		out($fptr,$sql);

		if ($structure_only!=true)
		{
			//parse out the table's data and generate the SQL INSERT statements in order to replicate the data itself...
			for ($c=0;$c<$nr;$c++)
			{
				$sql="insert into $tablename ($fl) values (";

				$row=mysql_fetch_row($res2);

				for ($d=0;$d<$nf;$d++)
				{
					$data=strval($row[$d]);
				
					if ($ina[$d]==true)
						$sql.= intval($data);
					else
						$sql.="\"".mysql_escape_string($data)."\"";

					if ($d<($nf-1)) $sql.=", ";
	
				}

				$sql.=");\n";

				out($fptr,$sql);

			}

			out($fptr,"\n\n");

		}

		mysql_free_result($res2);	

	}
	
	if ($fptr!=false) fclose($fptr);
	return 0;

}

function out($fptr,$s)
{
	if ($fptr==false) echo("$s"); else fputs($fptr,$s);
}



//------   Backup of config files ---------
if (getParam("backup","") == 1 && $set_demo!=1)
{
	

	function traverseDir($basedir, $AllDirectories=array()) {
	        $ThisDir=array();
	        chdir($basedir);
	        $current=getcwd();
	        
	        $handle=opendir(".");
	        while ($file = readdir($handle)) {
	                if (($file!='..') & ($file!='.')) {
	                        if (is_dir($file)) {
	                                #build an array of contents for this directory
	                                array_push($ThisDir,$current.'/'.$file);
	                        }
	                }
	        }
	        closedir($handle);
	        foreach ($ThisDir as $key=>$var) {
	                array_push($AllDirectories, $var);
	                $AllDirectories=traverseDir($var, $AllDirectories);
	        }
	        @chdir($basedir);
	        return $AllDirectories;
	}
	
	
	function getDirectoryContent($aBaseDirArray,$aSkipDirPattern)
	{
		$lDirectoryArray[]="";
		$lNewDirectoryArray[]="";
		$lDirectoryArray=array_merge($lDirectoryArray,$aBaseDirArray);	
		foreach ($aBaseDirArray as $item)
		{
			$lDirectoryArray=array_merge($lDirectoryArray,traverseDir($item));	
		}
		foreach ($lDirectoryArray as $item)
		{
			
			$plain_dir_array=split("/", $item); 
			$nb = count($plain_dir_array); 
			if ($nb>0) 
			  $nb = $nb-1; 
			else 
			  $nb = 0; 
			$plain_dir = $plain_dir_array[$nb]; 
			
			if (!in_array($plain_dir,$aSkipDirPattern))
				$lNewDirectoryArray[]=$item;
		
		}
		foreach ($lNewDirectoryArray as $item)
		{
			if (!empty($item))
			{
			$handle=opendir($item);
			
	        while ($file = readdir($handle)) 
	        {
	        	
				if (($file!='..') && ($file!='.')) 
				{
					if (!is_dir($file)) 
					{
	                	$lFileArray[]=$item . "/" . $file;
					
					}
				}
			}
			}
			
		}
		return $lFileArray;
	}
	
	
	$date = time();
	$filedate=date("Y-m-d");
	mysqlbackup("$set_mysql_host","$set_mysql_base","$set_mysql_user","$set_mysql_pass",$backup_dir . "mysql_$filedate.sql",false);
	
	// Set up what to do full backup of
	$lBaseDirArray[]=$set_path . "/admin/config";
	$lBaseDirArray[]=$set_path . "/images";
	$lBaseDirArray[]=$set_path . "/catimages";
	$lSkipDirArray[]="templates_c";
	$lSkipDirArray[]="backup";
	$lSkipDirArray[]="cache";
	$lBackupArray=getDirectoryContent($lBaseDirArray,$lSkipDirArray);
	$lBackupArray[]=$backup_dir . "mysql_$filedate.sql";
	echo "<p><b>".LA_ADMIN_BACKUP_DONE."</b></p>";
	$ziper = new zipfile();
	$ziper->addFiles($lBackupArray);
	$ziper->output("$backup_dir/$filedate.zip");
	@chmod ($backup_dir  . "$filedate.zip", 0777);
	@chmod ($backup_dir . "mysql_$filedate.sql", 0777);
	@unlink ($backup_dir . "mysql_$filedate.sql");
	
}






echo "<br /><br />" . LA_ADMIN_BACKUP_CURRENTS;

if (getParam("delzip",""))
{
	unlink("$backup_dir" . getParam("delzip",""));
	echo "Backup ".getParam("delzip","")." deleted<br /><br />";
}

$dir = opendir("$backup_dir");
while ($file = readdir($dir))
{
	if (eregi("zip",$file))
		$str.= "<tr><td>".substr($file,0,-4)."</td><td>" . date("H:i",filemtime($backup_dir . "$file"))."</td><td>" . round(filesize($backup_dir . "$file")/1024000,2) ." MB</td><td><img src='../layout_images/new/compress.gif' hspace='2' align='left'><a href='config/backup/$file'>Download</a></td><td><a href='?delzip=$file'>Delete</a></td></tr>" ;
}

if (!$str)
	echo "No backups.";
else 
	echo "<table width='600'><tr><td>Backup Date</td><td>Backup Clock</td><td>Backup Size</td><td>Download</td><td>Delete</td></tr>$str</table>";
	

}
else 
{
	echo "<font color='red'>Backup is disabled, but you may <a href='adm_set.php?file=opt_inc.php#set_backup'><b>activate it</b></a>.</font>";
	
}



writeCommonAdminTable("Backup","");
include("adm_footer.php");
?>